package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.autoconfig.templates.AipFaceTemplate;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.db.Question;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.model.vo.UserLikeListVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.tanhua.model.db.Settings;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @program: tanhua
 * @description:
 * @author: MR.peng
 * @create: 2022-03-08 21:04
 **/

@Service
public class UsersService {
    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private QuestionApi questionApi;//陌生人问题

    @DubboReference
    private SettingApi settingApi;//开关


    @DubboReference
    private BlackListApi blackListApi;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private MqMessageService mqMessageService;
    @Autowired
    private Unfreeze unfreeze;


    //根据id查询用户资料
    public UserInfoVo findUserINfoById(Long userId) {
        //1.查询对象
        UserInfo userInfo =  userInfoApi.findUser(userId);
        //2.将对象转化为Vo
        UserInfoVo Vo = new UserInfoVo();
        //企业中就是一个一个设置
        //教学：实体类和vo对象(大部分属性名和类型一致时)
        //Vo.setId(userInfo.getId());
        //Vo.setNickname(userInfo.getNickname());
        BeanUtils.copyProperties(userInfo,Vo);//将参数一的同名同类型属性，设置到参数二对象中
        //不同的，需要手动处理
        if(userInfo.getAge()!=null){
            Vo.setAge(userInfo.getAge().toString());
        }
        //3.返回Vo对象
        return Vo;
    }

    //更新用户信息
    public void updateUserInfo(UserInfo info) {
        userInfoApi.update(info);
    }

    /*查询通用设置*/
    public SettingsVo settings() {
        SettingsVo vo = new SettingsVo();
        Long userId = UserHolder.getUserId();
        //1.调用api,查询当前用户的陌生人问题(根据用户id查询)
        Question question = questionApi.findByUserId(userId);
        String txt = question == null ? "你喜欢java吗" : question.getTxt();
        vo.setStrangerQuestion(txt);
        //2.调用api,查询通知的开关
         Settings settings = settingApi.findUserById(userId);
         if(settings!=null){
             vo.setGonggaoNotification(settings.getGonggaoNotification());
             vo.setLikeNotification(settings.getLikeNotification());
             vo.setPinglunNotification(settings.getPinglunNotification());
         }
        //3.获取当前用户的手机号码
        String mobile = UserHolder.getUser().getMobile();
         vo.setPhone(mobile);
         vo.setId(userId);
        //4.返回
        return vo;
    }

    /*
    设置陌生人问题
        保存或者更新
    * */
    public void questions(String content) {
        //获取用户id
        Long userId = UserHolder.getUserId();
        //判断当前用户是否具有陌生人问题
        Question question = questionApi.findByUserId(userId);
        if (question == null){
            //问题对象不存在就是保存
            question = new Question();
            question.setUserId(userId);
            question.setTxt(content);
            questionApi.save(question);
        }else {
            //问题对象存在就是更新
            question.setTxt(content);
            questionApi.update(question);
        }
    }

    /*
    * 设置通知开关
    * */
    public void setting(Boolean like, Boolean pinglun, Boolean gonggao) {
        //1.获取用户id
        Long userId = UserHolder.getUserId();
        ///2.根据用户id，查询通知开关对象
        Settings settings = settingApi.findUserById(userId);
        //2.1如果对象不存在，添加
        if(settings == null){
            settings = new Settings();
            settings.setUserId(userId);
            settings.setLikeNotification(like);
            settings.setPinglunNotification(pinglun);
            settings.setGonggaoNotification(gonggao);
            settingApi.save(settings);
        }else{
            //2.2如果对象存在，更新
            settings.setLikeNotification(like);
            settings.setPinglunNotification(pinglun);
            settings.setGonggaoNotification(gonggao);
            settingApi.update(settings);
        }

    }

    /*
    * 查询黑名单用户数据(条件：用户id)
    * */
    public PageResult blacklist(Integer page, Integer pageSize) {
        //1.获取用户id
        Long userId = UserHolder.getUserId();
        //2.调用API根据用户id,分页查询黑名单数据
        IPage<UserInfo> ipage = blackListApi.findByUserId(userId,page,pageSize);
        //3.将IPage对象转化成PageResult
        PageResult vo = new PageResult(page,pageSize,ipage.getTotal(),ipage.getRecords());
       //4.返回
        return vo;
    }

    /*
    * 删除黑名单
    * */
    public void delBlackList(Long blackUserId) {

        //1.获取到用户id
        Long userId = UserHolder.getUserId();
        //2.调用api删除
        blackListApi.delete(userId,blackUserId);
    }
    //修改手机号校验验证码
    public Map checkVerificationCode(String phone, String code) {
        //判断验证码
        String redisCode = redisTemplate.opsForValue().get("SENDCODE:" + phone);
        boolean flag = true;
        Map map = new HashMap();
        if (StringUtils.isEmpty(code) || !code.equals(redisCode)) {
            flag = false;
        } else {
            //删除 redis code
            redisTemplate.delete("SENDCODE:" + phone);
        }
        map.put("verification", flag);
        return map;
    }

    //修改用户手机号
    public void update(User user) {
        userApi.update(user);
    }

    @DubboReference
    private VisitorsApi visitorsApi;

    //互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
    public PageResult findFriends(Integer type, Integer page, Integer pagesize) {
        if (type == 4){
            Long userId = UserHolder.getUserId();
            List<Visitors> list = visitorsApi.findAll(userId,page,pagesize);
            if (CollUtil.isEmpty(list)) {
                return new PageResult();
            }
            List<Long> userIds = CollUtil.getFieldValues(list, "visitorUserId", Long.class);
            Map<Long, UserInfo> infoMap = userInfoApi.findByIds(userIds);
            List<UserLikeListVo> vo = new ArrayList<>();
            for (Visitors visitors : list) {
                UserLikeListVo likeListVo = UserLikeListVo.init(infoMap.get(visitors.getVisitorUserId()), visitors);
                vo.add(likeListVo);
            }
            String key = Constants.VISITORS_USER + UserHolder.getUserId();
            Long time = System.currentTimeMillis();
            redisTemplate.opsForValue().set(key,time.toString());
            return new PageResult(page,pagesize,0L,vo);
        }
        return null;
    }

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private FriendApi friendApi;

    //互相喜欢，喜欢，粉丝 - 统计
    public Map counts(Long id) {
        return userLikeApi.counts(id);
    }

    //分页查询互相喜欢
    public PageResult eachLove(Integer type, Integer page, Integer pagesize) {
        if (type == 1) {
            //获取用户id
            Long id = UserHolder.getUserId();
            //查询好友
            List<Friend> list = friendApi.findByUserId(id,page, pagesize);
            if (CollUtil.isEmpty(list)) {
                return new PageResult();
            }

            //一次性查询
            List<Long> ids = CollUtil.getFieldValues(list, "friendId", Long.class);
            Map<Long, UserInfo> map = userInfoApi.findByIds(ids);

            //一个userLike构建一个UserLikeVo
            List<UserLikeListVo> vos = new ArrayList<>();
            for (Friend friend : list) {
                UserInfo userInfo = map.get(friend.getFriendId());
                UserLikeListVo vo = UserLikeListVo.init(userInfo, friend);
                vo.setAlreadyLove(true);
                vos.add(vo);
            }
            return new PageResult(page, pagesize, 0l, vos);
        }
        return null;
    }

    //分页查询喜欢
    public PageResult loveCount(Integer type, Integer page, Integer pagesize) {
        if (type == 2) {
            //获取用户id
            Long id = UserHolder.getUserId();

            //根据用户id查询喜欢的人id
            List<UserLike> likes = userLikeApi.findLove(id, page, pagesize);

            //判断
            if (CollUtil.isEmpty(likes)) {
                return new PageResult();
            }
            //一次性查询
            List<Long> ids = CollUtil.getFieldValues(likes, "likeUserId", Long.class);
            Map<Long, UserInfo> map = userInfoApi.findByIds(ids);

            //一个UserLike构建一个UserLikeVo
            List<UserLikeListVo> vos = new ArrayList<>();
            for (UserLike like : likes) {
                UserInfo userInfo = map.get(like.getLikeUserId());
                UserLikeListVo vo = UserLikeListVo.init(userInfo, like);
                vo.setAlreadyLove(true);
                vos.add(vo);
            }
            return new PageResult(page, pagesize, 0l, vos);
        }
        return null;
    }

    //分页查询粉丝
    public PageResult fanCount(Integer type, Integer page, Integer pagesize) {
        if (type == 3) {
            //获取用户id
            Long id = UserHolder.getUserId();
            //根据用户id查询喜欢的人id
            List<UserLike> likes = userLikeApi.findNotLove(id, page, pagesize);

            //判断
            if (CollUtil.isEmpty(likes)) {
                return new PageResult();
            }
            //一次性查询
            List<Long> ids = CollUtil.getFieldValues(likes, "userId", Long.class);
            Map<Long, UserInfo> map = userInfoApi.findByIds(ids);

            //一个UserLike构建一个UserLikeVo
            List<UserLikeListVo> vos = new ArrayList<>();
            for (UserLike like : likes) {
                UserInfo userInfo = map.get(like.getUserId());
                UserLikeListVo vo = UserLikeListVo.init(userInfo, like);
                Boolean huxiang = userLikeApi.huxiang(like.getUserId(), like.getLikeUserId());
                if (huxiang) {
                    vo.setAlreadyLove(true);
                }
                vos.add(vo);
            }
            return new PageResult(page, pagesize, 0l, vos);
        }
        return null;
    }


    //粉丝喜欢
    public void saveFans(Long uid) {
        //获取用户id
        Long id = UserHolder.getUserId();

        //构建UserLike对象
        UserLike like = new UserLike();
        like.setUserId(id);//用户id
        like.setLikeUserId(uid);//喜欢人的id
        like.setIsLike(true);
        like.setCreated(System.currentTimeMillis());//创建时间
        //保存
        userLikeApi.saveFans(like);
        //判断互相是否喜欢
        Boolean huXiang = userLikeApi.huxiang(id, uid);
        if (huXiang) {
            //喜欢加好友
            friendApi.save(id, uid);
            //注册环信
            huanXinTemplate.addContact("hx" + id, "hx" + uid);
        }
    }

    //取消喜欢
    public void notLike(Long uid) {
        //获取用户id
        Long id = UserHolder.getUserId();

        //判断是不是好友
        Boolean huxiang = userLikeApi.huxiang(id, uid);
        //删除数据库数据
        userLikeApi.delete(id, uid);
        if (huxiang) {
            //删除掉环信
            huanXinTemplate.deleteContact("hx" + id, "hx" + uid);
            //删除好关系
            friendApi.delete(id, uid);
        }
    }

    //是否喜欢（新增接口）
    public boolean alreadyLove(Long uid) {
        return userLikeApi.alreadyLove(uid,UserHolder.getUserId());
    }

}
